package com.web.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //设置请求编码
        req.setCharacterEncoding("UTF-8");
        //设置响应编码
        resp.setCharacterEncoding("UTF-8");
        //设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        //设置跨域的域名 * 代表所有
        resp.setHeader("Access-Control-Allow-Origin","*");
        ///设置跨域的方法
        resp.setHeader("Access-Control-Allow-Methods","*");
        ///设置跨域的头
        resp.setHeader("Access-Control-Allow-Headers","*");
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {
    }
}